
package logic.actions.query;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logic.actions.SEISaudeAction;
import logic.beans.DBElementIF;
import logic.forms.ElementForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import controller.SEISaudeDefaultFacade;

public class QueryElementsAction<E extends DBElementIF> extends SEISaudeAction {
	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception {
		ActionMessages errors = getErrors(request);
		ActionMessages messages = getMessages(request);
		
		if (isUserChecked() && !checkUserLogged(request)) {
			messages.add("store success",new ActionMessage("login.error.userName.mustLogin"));
			saveMessages(request,messages);
			
			return mapping.findForward("login");
		}
		
		Class<E> elementClass = (Class<E>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		SEISaudeDefaultFacade<E,Long> facade = SEISaudeDefaultFacade.getInstance(elementClass);
		ElementForm<E> myForm = (ElementForm<E>)form;
		myForm.setElementFromRequest(request);
		boolean keepForm = false;
		String actionParam = mapping.getParameter();
		
		if (actionParam != null) {
			if (actionParam.equals("query")) {
				keepForm = false;
				try {
					List<E> results = facade.getElementsByExample(myForm.getElement(),myForm.getEmptyPropertyNames());
					request.setAttribute("elementList",results);
					if (results.isEmpty()) keepForm = true;
				} catch (Exception ex) {
					keepForm = true;
					facade.clearCurrentSession();
					errors.add("query error",new ActionMessage("element.query.error",ex.getMessage()));
				}
			}
		}
		
		myForm.setRequestFromElement(request);
		saveErrors(request,errors);
		setUpRequest(facade,form,request);
		if (keepForm) request.setAttribute("element",myForm.getElement());
		
		return mapping.findForward("ok");
	}
}
